import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout'

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login', '/luoye', '/password-retrieval'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  const signStatus = localStorage.getItem('signStatus');
  NProgress.start() // start progress bar
  if (getToken()) { // determine if there has token
    /* has token*/
    if (to.path === '/login') {
      next({path: '/'})
      NProgress.done() // if current page is home will not trigger	afterEach hook, so manually handle it
    }
    else if (to.path === '/agentSignAgreement') {
      if (signStatus=='false') {
       next()
      }else{
        router.push('/')
      }
    } else {
      if (signStatus=='false') {
        router.push('/agentSignAgreement')
      }
      if (store.getters.refreshMenus) {
        let rou = JSON.parse(localStorage.getItem('router'));
        if(rou){
          rou.map(v => {
            if (v != null && v.path == null) {
              alert(v.title)
            }
          })
          rou = s(rou)
          store.dispatch('permission/setRefreshFasle')
          router.addRoutes(rou)
          store.dispatch('permission/setMenus', rou)
          next({...to, replace: true})
        }
      } else {
        next();
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      // if(to.path === '/agentSignAgreement'){
      //   next({ path: '/agentSignAgreement' })
      // }
      // else{// 否则全部重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
      // }

    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

function getChildren(nodeList, jsonData) {
  nodeList.forEach(function (elemet, index) {
    elemet.children = jsonData.filter(function (item, index) {
      return item.pid == elemet.id
    })
    if (elemet.children.length > 0) {
      getChildren(elemet.children, jsonData)
    }
  })
}

function s(l) {
  // let l = await getMenus({})
  var d = l
  var nd = []

  for (var t in d) {

    const p = d[t]
    if (p != null) {
      if (p.component == null || p.component == '') {
        p.component = Layout
      } else {
        const sk = p.component
        // console.log(p.title+","+sk)
        p.component = resolve => require([`@/${sk}`], resolve)
        //  p.component = () => import(`@/views/permission-management/employee-management/index`)
      }
      var obj = {
        id: p.id,
        pid: p.pid,
        path: p.path,
        hidden: p.hidden,
        component: p.component,
        name: p.name,
        meta: {title: p.title, icon: p.icon}
      }
      //console.log(obj)
      nd.push(obj)
    }
  }
  var resultObj = []
  var baseNode = nd.filter(element => {
    return element.pid == 0
  })
  resultObj.push(...baseNode)
  getChildren(resultObj, nd)
  resultObj.push({path: '*', redirect: '/404', hidden: true})
  return resultObj
}
